package kubeclient

import (
	"context"
	v1 "k8s.io/api/core/v1"
	v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
)

type ServiceKubeController struct {
	*KubeController
}

func (skc *ServiceKubeController) Get(namespace string, name string) (interface{}, error) {
	return skc.serviceLister.Services(namespace).Get(name)
}

func (skc *ServiceKubeController) Create(namespace string, applicationName string) (interface{}, error) {
	service := InitService(namespace, applicationName+"-service", applicationName)
	return skc.clientSet.CoreV1().Services(namespace).Create(context.TODO(), service, v12.CreateOptions{})
}

func (skc *ServiceKubeController) Delete(namespace string, applicationName string) error {
	serviceName := applicationName + "-service"
	return skc.clientSet.CoreV1().Services(namespace).Delete(context.TODO(), serviceName, v12.DeleteOptions{})
}

func InitService(namespace string, serviceName string, labelName string) *v1.Service {
	service := v1.Service{}

	service.Namespace = namespace
	service.Name = serviceName
	service.Labels = make(map[string]string)
	service.Labels["app"] = labelName
	spec := v1.ServiceSpec{}

	spec.Ports = []v1.ServicePort{}
	port := v1.ServicePort{}
	port.Port = 80
	port.TargetPort = intstr.IntOrString{IntVal: 80}
	spec.Ports = append(spec.Ports, port)

	spec.Selector = make(map[string]string)
	spec.Selector["app"] = labelName
	service.Spec = spec

	return &service
}
